var express = require('express');
var router = express.Router();
var md5 = require("md5");

var userDAO = require("../bin/db/userDAO.js");

router.post("/regist",(req,res)=>{
  userDAO.findOne({tel:req.body.tel})
  .then(data=>{
    if(data){
      res.json({err:1,msg:"该手机号已被占用！"});
    }else{
      var u = new userDAO(req.body);
      u.psw = md5(u.psw);
      u.save()
      .then(data=>{
        res.json({err:0,msg:"注册成功！"});
      });
    }
  })
  
});

// 登录接口
router.post("/pswlogin",(req,res)=>{
  req.body.psw = md5(req.body.psw);
  userDAO.findOne(req.body,{psw:0})
  .then(data=>{
    if(data){
      req.session.user = data;
      res.json({err:0,msg:"登录成功！",data});
    }else{
      res.json({err:1,msg:"手机号或密码不正确！"});
    }
  });
});

// 退出登录的接口
router.post("/exit",(req,res)=>{
  req.session.user = null;
  res.json({err:0,msg:"退出登录！"});
});

module.exports = router;
